package com.sciencep.pro.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.IntStream;

public class StringUtil {

    private static final Pattern p = Pattern.compile("[0-9a-zA-Z]{1,}");

    private StringUtil() {

    }

    /**
     * 驼峰转下划线
     *
     * @param value 待转换值
     * @return 结果
     */
    public static String camelToUnderscore(String value) {
        if (StringUtils.isBlank(value)) {
            return value;
        }
        String[] arr = StringUtils.splitByCharacterTypeCamelCase(value);
        if (arr.length == 0) {
            return value;
        }
        StringBuilder result = new StringBuilder();
        IntStream.range(0, arr.length).forEach(i -> {
            if (i != arr.length - 1) {
                result.append(arr[i]).append(StringPool.UNDERSCORE);
            } else {
                result.append(arr[i]);
            }
        });
        return StringUtils.lowerCase(result.toString());
    }

    public static Object jsonStringToMap(String jsonString) {
        Object object;
        try {
            object = JSON.parse(jsonString);
        } catch (Exception e) {
            object = jsonString;
        }
        if (!(object instanceof JSONObject)) {
            return object;
        }
        Map<String, Object> map = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(jsonString);
        for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
            Object o = entry.getValue();
            if (o instanceof JSONArray) {
                List<Object> list = new ArrayList<>();
                Iterator<Object> it = ((JSONArray) o).iterator();
                while (it.hasNext()) {
                    Object obj = it.next();
                    list.add(jsonStringToMap(obj.toString()));
                }
                map.put(entry.getKey(), list);
            } else if (o instanceof JSONObject) {
                // 如果内层是json对象的话，继续解析
                map.put(entry.getKey(), jsonStringToMap(o.toString()));
            } else {
                // 如果内层是普通对象的话，直接放入map中
                if (o instanceof String) {
                    map.put(entry.getKey(), o.toString().trim());
                } else {
                    map.put(entry.getKey(), o);
                }
            }
        }
        return map;
    }


    /**
     * 匹配字符串是否是数字和字母组成
     *
     * @param s
     * @return
     */
    public static boolean isAlphaNumeric(String s) {
        Matcher m = p.matcher(s);
        return m.matches();
    }

}
